package com.pray.aop;

import com.pray.annotation.Restrict;
import com.pray.common.RestrictHandler;
import com.pray.common.UserHolder;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

/**
 * <p>
 * RestrictAcpect
 * <p>
 *
 * @author 春江花朝秋月夜
 * @since 2023/8/24
 */
@Aspect
@Component
public class RestrictAspect {
    @Resource
    HttpServletRequest request;
    @Resource
    RestrictHandler handler;
    @Before(("@annotation(restrict)"))
    public void before(JoinPoint joinPoint, Restrict restrict){
        int id = UserHolder.getLocalUser().getId();
        String key= request.getRequestURI()+id;

        int limit=restrict.limit();
        int time= restrict.time();

        handler.setLimit(limit);
        handler.setTime(time);

        handler.init(key,limit,time);
        boolean res= handler.check(key,limit);
        if (res){
            throw new RuntimeException("访问次数过多，请稍后再试试？");
        }
    }
}
